﻿using Furion;
using Furion.DynamicApiController;
using FurionApiDemo.Core;
using FurionApiDemo.Core.ApiResult;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace FurionApiDemo.Application.Services
{
    /// <summary>
    /// 文件服务接口
    /// </summary>
    [Route("File")]
    public class FilesAppService : IDynamicApiController
    {
        private readonly ILogger<FilesAppService> _logger;

        public FilesAppService(ILogger<FilesAppService> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadFile")]
        [Authorize]
        public async Task<string> UploadFile(IFormFile file)
        {
            var result = "";
            try
            {
                // 如：保存到网站根目录下的 uploads 目录
                var savePath = Path.Combine("D:\\Web\\UpdateWeb\\investigationCoverImage");
                if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);

                //// 这里还可以获取文件的信息
                // var size = file.Length / 1024.0;  // 文件大小 KB
                // var clientFileName = file.FileName; // 客户端上传的文件名
                //var contentType = file.ContentType; // 获取文件 ContentType 或解析 MIME 类型

                var suffix = file.FileName.Split(".")[file.FileName.Split(".").Length - 1];
                // 避免文件名重复，采用 GUID 生成
                var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
                var filePath = Path.Combine(savePath, fileName);

                // 保存到指定路径
                using (var stream = System.IO.File.Create(filePath))
                {
                    await file.CopyToAsync(stream);
                }
                result = fileName;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

            // 在动态 API 直接返回对象即可，无需 OK 和 IActionResult
            return result;
        }

    }
}
